#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 
#include <arpa/inet.h>

#define CLIENT_BUF_SIZE 256

void error(const char *msg) {
    perror(msg);
    exit(0);
}

int main(int argc, char *argv[]) {
    int sockfd, portno;
    char send_buf[CLIENT_BUF_SIZE], recv_buf[CLIENT_BUF_SIZE];
    struct sockaddr_in serv_addr;

    if (argc < 3) {
      fprintf(stderr,"Usage: %s hostname port\n", argv[0]);
      exit(0);
    }

    /* Create socket */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) 
       error("socket");

    /* Create network address */
    bzero(&serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    if (inet_pton(AF_INET, argv[1], &serv_addr.sin_addr) <= 0) { // Convert IP address from string to network address
        error("inet_pton");
    }
    portno = atoi(argv[2]);
    serv_addr.sin_port = htons(portno);

    /* Use socket to connect */
    if (connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) 
       error("connect");

    printf("Client connect to server %s port %s\n", argv[1], argv[2]);

    while (fgets(send_buf, sizeof(send_buf), stdin) != NULL) {
        if (write(sockfd, send_buf, strlen(send_buf)) < 0) {
            perror("write");
        }
        // bzero(recv_buf, sizeof(recv_buf));
        // read(sockfd, recv_buf, sizeof(recv_buf));
        // printf("peer: %s", recv_buf);
        bzero(send_buf, sizeof(send_buf));
    }

    close(sockfd);

    return 0;
}
